<template>
  <el-page-header @back="router.go(-1)" title="返回">
    <template #content>
      <span>{{resourceForm.id ? '编辑':'添加'}}资源</span>
    </template>
  </el-page-header>

  <div class="content">
    <el-form ref="resourceFormRef" :model="resourceForm" :rules="resourceFormRule" :inline="false" label-width="160px">

      <el-form-item label="名称" prop="name">
        <el-input v-model="resourceForm.name" placeholder="请输入名称" maxlength="20"/>
      </el-form-item>
 

      <el-form-item label="分类" prop="resourceTypeId">
        <el-select style="width:200px" v-model="resourceForm.resourceTypeId" placeholder="请选择分类">
          <el-option v-for="(item, index) in resouceTypeList" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="文件url" prop="url"> 

        <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          action="http://localhost/file/upload"
          :before-remove="beforeRemove"
          :on-exceed="handleExceed"
          :limit="1"  
          :headers="{token:token}" 
          :on-success="handleSuccess"
          :before-upload="beforeAvatarUpload">
          <el-button type="primary">上传</el-button>
          <template #tip>
            <div class="el-upload__tip"> 
              文件大小不能超过1M(同学这个属性根据你在后台上传限制决定的)
            </div>
          </template>
        </el-upload>

      </el-form-item>

      <el-form-item label="描述">
        <el-input v-model="resourceForm.description" type="textarea" />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleSave">保存</el-button>
        <el-button type="primary" @click="handleCancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router";

import type {UploadProps,UploadUserFile } from 'element-plus'
import {ElMessageBox,ElMessage} from 'element-plus'

import {saveResource,findById} from "@/api/resource"
import {getResourceTypeList} from "@/api/resourceType"
 
  
const router = useRouter();
const route = useRoute();
 
const token = sessionStorage.getItem("token");

const fileList = ref<UploadUserFile[]>([
  
])

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `最多只能上传一个文件, 已经上传了 ${files.length} 个文件`
  )
}
   
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `是否删除 ${uploadFile.name} 文件 ?`
  ).then(
    () => true,
    () => false
  )
}


//图片上传相关方法
const handleSuccess=(resp, file)=>{
  resourceForm.url = resp.data;

  fileList.value.push({"name":file.name,"url":resp.data});
}

const beforeAvatarUpload=(file)=>{ 
  const isLt2M = file.size / 1024 / 1024 < 2; 
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 1MB!');
  }
  return isLt2M;
}


let resourceFormRef = reactive(null);

let resourceForm = reactive({
  id:null,
  name: null,
  resouceTypeId:null,
  url:null,
  description:null
});

  

let resourceFormRule = reactive({
  name: [
    {
      required: true,
      trigger: 'blur'
    }
  ],
  url: [
    {
      required: true,
      trigger: 'blur'
    }
  ]
})
 
const resouceTypeList = reactive([]);

//加载资源分类信息
getResourceTypeList().then(resp=>{
  resouceTypeList.push(... resp.data);
})

  

if(route.query.resourceId){
  //根据id查找
  findById(route.query.resourceId).then((resp)=>{
    let resource = resp.data;
    resourceForm.id = resource.id;
    resourceForm.name = resource.name;
    resourceForm.resouceTypeId = resource.resouceTypeId;
    resourceForm.url = resource.url; 
    resourceForm.description = resource.description; 
  }).catch((error)=>{

  })
}

let handleSave = () => {
  //判断是否校验通过
  resourceFormRef.validate((valid) => {
    if (valid) { 
      saveResource(resourceForm.id,resourceForm).then((resp) => {
        //提示并且返回列表
        router.push({path: '/resource/list'});
      });
    }
  });
}
</script>

<style scoped>
.content {
  margin-top: 40px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
